package com.demo.controller;

import com.demo.common.Result;
import com.demo.pojo.dto.ScheduleListDTO;
import com.demo.pojo.entity.Teacher;
import com.demo.service.TeacherUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * 教师用户控制器
 */
@RestController
@RequestMapping("/teacher-user")
@CrossOrigin
public class TeacherUserController {
    
    @Autowired
    private TeacherUserService teacherUserService;
    
    /**
     * 教师登录
     */
    @PostMapping("/login")
    public Result<Teacher> teacherLogin(@RequestParam String teNo, @RequestParam String password) {
        try {
            Teacher teacher = teacherUserService.teacherLogin(teNo, password);
            if (teacher != null) {
                return Result.success(teacher);
            } else {
                return Result.error("登录失败，工号或密码错误");
            }
        } catch (Exception e) {
            return Result.error("登录失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取教师个人信息
     */
    @GetMapping("/info/{teacherId}")
    public Result<Teacher> getTeacherInfo(@PathVariable Long teacherId) {
        try {
            Teacher teacher = teacherUserService.getTeacherInfo(teacherId);
            return Result.success(teacher);
        } catch (Exception e) {
            return Result.error("获取教师信息失败：" + e.getMessage());
        }
    }
    
    /**
     * 更新教师个人信息
     */
    @PutMapping("/update")
    public Result<String> updateTeacherInfo(@RequestBody Teacher teacher) {
        try {
            boolean success = teacherUserService.updateTeacherInfo(teacher);
            if (success) {
                return Result.success("更新教师信息成功");
            } else {
                return Result.error("更新教师信息失败");
            }
        } catch (Exception e) {
            return Result.error("更新教师信息失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取教师课表
     */
    @GetMapping("/schedule/{teacherId}/{semester}")
    public Result<List<ScheduleListDTO>> getTeacherSchedule(@PathVariable Long teacherId, 
                                                          @PathVariable String semester) {
        try {
            List<ScheduleListDTO> schedules = teacherUserService.getTeacherSchedule(teacherId, semester);
            return Result.success(schedules);
        } catch (Exception e) {
            return Result.error("获取教师课表失败：" + e.getMessage());
        }
    }

    /**
     * 获取教师课表（学期可选，后端做兜底：advanced -> 2025-1）
     */
    @GetMapping("/schedule/{teacherId}")
    public Result<List<ScheduleListDTO>> getTeacherScheduleFallback(
            @PathVariable Long teacherId,
            @RequestParam(value = "semester", required = false) String semester) {
        try {
            String resolved = semester;
            if (resolved == null || resolved.isBlank()) {
                resolved = "advanced";
            }
            List<ScheduleListDTO> schedules = teacherUserService.getTeacherSchedule(teacherId, resolved);
            if ((schedules == null || schedules.isEmpty()) && !"2025-1".equals(resolved)) {
                // 兜底尝试另一个常用学期
                schedules = teacherUserService.getTeacherSchedule(teacherId, "2025-1");
            }
            return Result.success(schedules);
        } catch (Exception e) {
            return Result.error("获取教师课表失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取教师本周课表
     */
    @GetMapping("/schedule/week/{teacherId}/{semester}/{weekNo}")
    public Result<List<ScheduleListDTO>> getTeacherWeekSchedule(@PathVariable Long teacherId, 
                                                              @PathVariable String semester, 
                                                              @PathVariable Integer weekNo) {
        try {
            List<ScheduleListDTO> schedules = teacherUserService.getTeacherWeekSchedule(teacherId, semester, weekNo);
            return Result.success(schedules);
        } catch (Exception e) {
            return Result.error("获取教师本周课表失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取教师今日课表
     */
    @GetMapping("/schedule/today/{teacherId}/{semester}/{weekNo}/{dayOfWeek}")
    public Result<List<ScheduleListDTO>> getTeacherTodaySchedule(@PathVariable Long teacherId, 
                                                               @PathVariable String semester, 
                                                               @PathVariable Integer weekNo, 
                                                               @PathVariable Integer dayOfWeek) {
        try {
            List<ScheduleListDTO> schedules = teacherUserService.getTeacherTodaySchedule(teacherId, semester, weekNo, dayOfWeek);
            return Result.success(schedules);
        } catch (Exception e) {
            return Result.error("获取教师今日课表失败：" + e.getMessage());
        }
    }
    
    /**
     * 申请调课
     */
    @PostMapping("/schedule/change")
    public Result<String> applyScheduleChange(@RequestParam Long scheduleId, 
                                            @RequestParam String reason, 
                                            @RequestParam Long newTimeSlotId, 
                                            @RequestParam Long newClassroomId) {
        try {
            boolean success = teacherUserService.applyScheduleChange(scheduleId, reason, newTimeSlotId, newClassroomId);
            if (success) {
                return Result.success("调课申请提交成功");
            } else {
                return Result.error("调课申请提交失败");
            }
        } catch (Exception e) {
            return Result.error("调课申请提交失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取教师工作量统计
     */
    @GetMapping("/workload/{teacherId}/{semester}")
    public Result<Map<String, Object>> getTeacherWorkloadStats(@PathVariable Long teacherId, 
                                                              @PathVariable String semester) {
        try {
            Map<String, Object> stats = teacherUserService.getTeacherWorkloadStats(teacherId, semester);
            return Result.success(stats);
        } catch (Exception e) {
            return Result.error("获取教师工作量统计失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取教师时间偏好
     */
    @GetMapping("/preference/{teacherId}")
    public Result<Map<String, Object>> getTeacherTimePreference(@PathVariable Long teacherId) {
        try {
            Map<String, Object> preferences = teacherUserService.getTeacherTimePreference(teacherId);
            return Result.success(preferences);
        } catch (Exception e) {
            return Result.error("获取教师时间偏好失败：" + e.getMessage());
        }
    }
    
    /**
     * 设置教师时间偏好
     */
    @PostMapping("/preference/{teacherId}")
    public Result<String> setTeacherTimePreference(@PathVariable Long teacherId, 
                                                 @RequestBody Map<String, Object> preferences) {
        try {
            boolean success = teacherUserService.setTeacherTimePreference(teacherId, preferences);
            if (success) {
                return Result.success("设置教师时间偏好成功");
            } else {
                return Result.error("设置教师时间偏好失败");
            }
        } catch (Exception e) {
            return Result.error("设置教师时间偏好失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取教师的学生列表
     */
    @GetMapping("/students/{teacherId}/{semester}")
    public Result<List<Map<String, Object>>> getTeacherStudents(@PathVariable Long teacherId,
                                                                @PathVariable String semester) {
        try {
            System.out.println("===== 获取教师学生列表 =====");
            System.out.println("教师ID: " + teacherId);
            System.out.println("学期: " + semester);
            
            List<Map<String, Object>> students = teacherUserService.getTeacherStudents(teacherId, semester);
            
            System.out.println("查询到学生数量: " + (students != null ? students.size() : 0));
            
            return Result.success(students);
        } catch (Exception e) {
            System.err.println("获取学生列表失败，详细错误：");
            e.printStackTrace();
            return Result.error("获取学生列表失败：" + e.getMessage());
        }
    }
}


